import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import json
import plotly
import pandas as pd
from datetime import datetime
from pprint import pprint

from auto_notify.daemon_fetch_db_feed import get_table_source, start_loop_notify
from config import config
import numpy as np
import pymongo
import os
import time

from dash_lib.mongodb_helper import mongo_db, update_feed
last_n_clcik = 0
readed_list=get_table_source(True)
app = dash.Dash()

app.layout = html.Div([
    html.Button('START LOOP', id='btn_start_loop', style={'margin-bottom': '15' }),

    dt.DataTable(
        rows=get_table_source(False),
        min_width=1350,
        min_height=200,
        # optional - sets the order of columns
        # columns=sorted(DF_SIMPLE.columns),
        editable=True,
        id='dt_base_info',

    ),
    html.Button('update_all', id='btn_update_all', style={'margin-bottom': '30','margin-top': '30'}),
    dt.DataTable(
        rows=readed_list,
        min_width=1350,
        min_height=700,
        # optional - sets the order of columns
        # columns=sorted(DF_SIMPLE.columns),
        editable=False,
        id='dt_base_info_has_read',

    )
]
)



def update_last_click(n_clicks):
    global last_n_clcik
    last_n_clcik = n_clicks


@app.callback(
    dash.dependencies.Output('dt_base_info', 'rows'),
    [Input('btn_update_all', 'n_clicks')],
    [State('dt_base_info', 'rows')])
def update_output(n_clicks, rows):
    if n_clicks != None:
        if n_clicks > last_n_clcik:
            update_feed(rows)
    update_last_click(last_n_clcik)
    return get_table_source(False)


@app.callback(
    dash.dependencies.Output('dt_base_info_has_read', 'rows'),
    [Input('btn_update_all', 'n_clicks')])
def update_output_readed(n_clicks):
    return get_table_source(True)


@app.callback(
    dash.dependencies.Output('btn_start_loop', 'value'),
    [Input('btn_start_loop', 'n_clicks')])
def update_output(n_clicks):
    run_loop_notify_py()
    return ' looping '


#
# @app.callback(
#     Output('datatable-gapminder', 'selected_row_indices'),
#     [Input('graph-gapminder', 'clickData')],
#     [State('datatable-gapminder', 'selected_row_indices')])
# def update_selected_row_indices(clickData, selected_row_indices):
#     if clickData:
#         for point in clickData['points']:
#             if point['pointNumber'] in selected_row_indices:
#                 selected_row_indices.remove(point['pointNumber'])
#             else:
#                 selected_row_indices.append(point['pointNumber'])
#     return selected_row_indices


# @app.callback(
#     Output('dt_base_info', 'rows'),
#     [Input('tipper_search', 'value'),
#      ])
# def update_pick_type(tipper_search):
#     base_df = analyse_data.init(tipper_search)
#
#     base_pivot_table = pd.pivot_table(base_df, values=['profit'], index=['pick_type', 'sport', 'stake'],
#                                       aggfunc=[len, np.mean, np.sum, np.median, np.max], fill_value=0, margins=False)
#     pivot_table_len_profit_ = base_pivot_table[base_pivot_table[('len', 'profit')] > 11]
#
#     # pivot_table => dataframe=>dict
#     df = pd.DataFrame(pivot_table_len_profit_.to_records())
#     df=df.round(2)
#     print('##############@@@@@@@@@@@@@@@@@')
#     print(df)
#     return df

app.css.append_css({
    'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})


def run_loop_notify_py():
    print('start_loop_notify')
    start_loop_notify()


if __name__ == '__main__':
    app.run_server(debug=True, port=8002)
